package com.zlb.app.utils;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;


/**
 * Json 工具类 使用FastJson重新写了代码，性能有大幅度提升，并且减少了内存和CPU消耗
 */
public class JsonUtil {
	/**
	 * <pre>
	 * 调用示例：
	 *      String json = "{\"status\": {\"code\": 1001,\"msg\": \"正常\"},\"result\": {\"data\": {\"is_end\": false,\"userId\": \"helo_kitty\"}}}";
	 *      JSONObject jsonObject = JSONObject.parseObject(json);
	 *      Object lastTweetId = JSONUtils.select(jsonObject, "result.data.userId");
	 *      System.out.println(lastTweetId);
	 * ---- print：
	 * helo_kitty
	 * </pre>
	 *
	 * @return
	 */
	public static Object select(JSONObject jsonObj, String keyPath) {
		if (null == jsonObj || null == keyPath) {
			return null;
		}
		String[] patharr = keyPath.split("\\.");
		JSONObject current = jsonObj;
		Object retvalue = null;
		for (int i = 0; i < patharr.length; i++) {
			String key = patharr[i];
			if(ObjectUtil.isEmpty(current)){
				continue;
			}
			retvalue = current.get(key);
			if (i < (patharr.length - 1)) {
				current = (JSONObject) retvalue;
			}
		}
		return retvalue;
	}
}
